
//
//  DDSendStatusVC.swift
//  SinaMicroBlogSwift2
//
//  Created by dqw on 15/8/5.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

// MARK: - 重点：1. 各View加载方法的执行顺序，2. 约束不可以重复加载，更换前要先删除上一个约束，3. 即要求视图层次的，又有相互之间的约束，可以先讲各View按顺序添加，然后在按照另外的顺序添加约束，即将二者分开。4？？ 但是添加第一个表情图片的额时候，发送没有被激活还是没有解决。
private let kMaxStatusLength = 10
extension DDSendStatusVC: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        print(textView.hasText())
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        placeLabel.hidden = textView.hasText()
      print(textView.attributedText.length)
        
        let count = kMaxStatusLength - (self.textView.emoticonText()?.characters.count)!
        tipLabel.text = String(count)
        tipLabel.textColor = count < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
    }
}
class DDSendStatusVC: UIViewController
{
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
      addKeyboarNotification()
        
    }
    // 先退出键盘在销毁控制器。
     func close() {
       textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    // 以打开就推出键盘。
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
        navigationItem.rightBarButtonItem?.enabled = pictuerSelectorVC.images.count > 0
    }
    override func viewWillDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        textView.resignFirstResponder()
    }
    override func loadView() {
        super.loadView()
        // 如果放在did appear里面的话，在选择图片后会提示过度布局。
        configureView()

    }
    
    private func addKeyboarNotification() {
          NSNotificationCenter.defaultCenter().addObserver(self, selector: "pushKeybobard:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    private func removeKeyboardNotification() {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func pushKeybobard(not: NSNotification) {
     
        let rect = not.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        let duration = not.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        // 和刷到几条微博的动画对比，uiview的animation是把变化放在block里面。那个地方用的是CGRectOffset。
        toolbarBottom?.constant = -(UIScreen.mainScreen().bounds.height - rect.origin.y)
        
        print(toolbarBottom?.constant)
        print(rect.origin.y)
        
        
        UIView.animateWithDuration(duration) { () -> Void in
            // 如果加这句话的话，则在弹出键盘的时候，可以将注销和添加通知移除，但是此属性会导致duration无效。
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: 7)!)
            
            self.view.layoutIfNeeded()
        }
    }

    deinit {
        removeKeyboardNotification()
    }
    private func configureNav() {
        
        let titleView = UIView()
        navigationItem.titleView = titleView
        
        let titleLabel = UILabel(text: "新浪微博", color: UIColor.darkTextColor(), fontSize: 18)
        let namelabel = UILabel(text: (DDUserAccount.aUserAccount?.name)!, color: UIColor.darkGrayColor(), fontSize: 14)
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(namelabel)
        
        titleLabel.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
        namelabel.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
    }
    
    func sendStatus() {
        
       let status = textView.emoticonText()!
        if status.characters.count > kMaxStatusLength {
            SVProgressHUD.showInfoWithStatus("你输入的文本太长le", maskType: SVProgressHUDMaskType.Gradient)
            return
        }
      let image =  pictuerSelectorVC.images.last
        DDNetTools.sharedNetTools.sendStatus(status, image: image) { (result, error) -> () in
            if error != nil {
                SVProgressHUD.showInfoWithStatus("你的网络不给力")
            }
            self.close()
        }
    }
    
        // MARK:- 键盘控制器要强引用，因为self.view 对其View有引用，但是不能保证VC不被销毁。weak self  self？？？
    private lazy var emoticonVC: DDEmoticonVC = DDEmoticonVC {[weak self] (emoticon) -> Void in
        self?.textView.insertEmoticon(emoticon)
    }
    // FIXME: toolbar 运动过快，会出现弹簧效果，出乎意料。通过及时的移除和添加通知解决。
    func inputEmoticon() {
        
//        removeKeyboardNotification()
        textView.resignFirstResponder()
        textView.inputView = (textView.inputView == nil) ? emoticonVC.view : nil
//        addKeyboarNotification()
        textView.becomeFirstResponder()
        
    }
    private func configureView() {
        
        addChildViewController(pictuerSelectorVC)
        view.addSubview(textView)
        view.addSubview(pictuerSelectorVC.view)
        view.addSubview(toolbar)
//        pictureViewHeightCon?.constant = 0
   
        configureNav()
        configureToolBar()
        configurePictuerSelectorView()
        configureTextView()

    }
    
    var  toolbarBottom: NSLayoutConstraint?
    private func configureToolBar() {
        
        let cons = toolbar.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
        toolbarBottom = toolbar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        toolbar.backgroundColor = UIColor.darkGrayColor()
        // 多个固定数据，可以考虑将其放在数组或者字典里面调用。
        let itemSettings = [["imageName": "compose_toolbar_picture",  "action": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        var items = [UIBarButtonItem]()
        
        for dict in itemSettings {
            items.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, action: dict["action"]))
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        // 去掉最后一个弹簧。
        items.removeLast()
        toolbar.items = items
    }
    
    var selectPictureFlag = false
    func selectPicture() {
        
//       pictureViewHeightCon?.constant = (textView.inputView == nil) ? UIScreen.mainScreen().bounds.size.height * 0.6 : 0
        selectPictureFlag = !selectPictureFlag
        pictureViewHeightCon?.constant = selectPictureFlag ?  UIScreen.mainScreen().bounds.size.height * 0.6 : 0
        let textViewReferView = selectPictureFlag ? pictuerSelectorVC.view : toolbar
//        textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: textViewReferView, size: nil)
        print(textViewBottom!)
        view.removeConstraint(textViewBottom!)
//        textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: pictuerSelectorVC.view, size: nil)
        textViewBottom = NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: textViewReferView, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0)
        view.addConstraint(textViewBottom!)
//        textViewBottom = view.constraints.last

        
    }
    var pictureViewHeightCon: NSLayoutConstraint?
    private func configurePictuerSelectorView() {
        
        var s = UIScreen.mainScreen().bounds.size
//        s.height =   0.6 * s.height
        s.height = 0.0
       let cons = pictuerSelectorVC.view.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: s)
        pictureViewHeightCon = pictuerSelectorVC.view.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
    }
    
    var textViewBottom: NSLayoutConstraint?
    private func configureTextView() {
        
        textView.delegate = self
        textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
      let cons =  textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolbar, size: nil)
        textViewBottom = textView.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
//        textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: pictuerSelectorVC.view, size: nil)
        textView.addSubview(placeLabel)
        placeLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: textView, size: nil, offset: CGPoint(x: 5, y: 8))
        view.addSubview(tipLabel)
        tipLabel.ff_AlignInner(type: ff_AlignType.BottomRight, referView: textView, size: nil, offset: CGPoint(x: -5, y: -5))
    }
    
    private lazy var pictuerSelectorVC = DDPictureSelectorVC()
    private lazy var tipLabel: UILabel = {
        let ll = UILabel()
        ll.font = UIFont.systemFontOfSize(14)
        ll.text = String(kMaxStatusLength)
        ll.sizeToFit()
        return ll
    }()
    private lazy var toolbar = UIToolbar()
    private lazy var placeLabel: UILabel = UILabel(text: "记录心情", color: UIColor.lightGrayColor(), fontSize: 18)
    private lazy var textView:UITextView = {
       
        let tv = UITextView()
        // 这句话不能少，有了这些后，就有了字体，不然如果一杀过来就输入图片的话字体解包失败。
//        tv.text = "记录心情"
        tv.font = UIFont.systemFontOfSize(18)
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
//        tv.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
        tv.alwaysBounceVertical = true
        tv.backgroundColor = UIColor.whiteColor()
        tv.textColor = UIColor.lightGrayColor()
        return tv
    }()
   }
 